# Python-CPP Query processor interface
#
# NYU:Poly
# Juan Rodriguez
#

from ctypes import *

# single result 
class RESULT(Structure):
    _fields_ = [("score",c_double),
                ("docid",c_ulong),
                ("url",c_char_p)]

# pointer to results list (in C++)
Results_Table = POINTER(RESULT)

# wrapper for CPP query processor
lib = CDLL('/home/weijiang/workspace/polyIRToolkit/testCodePlayGround/libpyTest')
# lib = CDLL('/data1/team/weijiang/machine-learning-project-related/programs/polyIRToolkit/polyIRIndexer/irtk.so')

# prototype for the callback function
CMPFUNC = CFUNCTYPE(c_int, c_int, c_int, POINTER(RESULT))

# callback prototype for results
#   paramaters:
#       query id
#       number of entries
#       pointer to results
#   returns int 0 to C code when done 
#
def callback(qid, numResults, results_ptr):
    print "Got ", numResults, "results for query:", qid
    Results = cast(results_ptr,POINTER(RESULT))
    for item in Results:
		# list is null terminated
        if item.url is None:
            break
		# do something with the results
        print "Score: ", item.score, ", DocID: ", item.docid, ", URL: ", item.url
    return 0

# proxy query processor object
class Foo(object):

    def __init__(self, top_k):
        self.foo = lib.Foo_new(top_k)

    def __del__(self):
        lib.Foo_delete(self.foo)
        
    # push a query for processing
    #   paramaters:
    #       query id
    #       query string
    #       callback function
    def push(self, queryId, query):
        lib.Foo_push(self.foo, queryId, query, CMPFUNC(callback))

		
# HOW TO USE
# ----------

topK = 10

# CPP query processor proxy, want topK 
f = Foo(topK)

# push some queries to the query processor
f.push(1,"Yellow banana") 
f.push(2,"Yellow submarine") 
f.push(3,"penguin")

print "program end"

